<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
import { ElMessage, FormInstance, FormRules } from 'element-plus'
import { saveSysDict, updateSysDict } from '@/api/system'
import { ApiResult } from '@/utils'

interface IDate {
  id: string
  parentId: string
  name: string
  code: string
  remark: string
  sort: string | number
  state: string | number
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object,
    default: () => {}
  },
  type: {
    type: String,
    default: '1' // 1 字典编码 | 2 字典值
  }
})

const emit = defineEmits(['update:visible', 'update:data', 'submit'])

const ruleFormRef = ref()
const submitLoading = ref<boolean>(false)

const formData = reactive<IDate>({
  id: '',
  parentId: '',
  code: '',
  name: '',
  remark: '',
  sort: 1,
  state: 1
})

const rules = reactive<FormRules<IDate>>({
  code: [{ required: true, message: '请输入', trigger: 'blur' }],
  name: [{ required: true, message: '请输入', trigger: 'blur' }]
})

const dialogVisible = computed({
  get() {
    return props.visible
  },

  set(visible: boolean) {
    emit('update:visible', visible)
  }
})

const title = computed(() => {
  return formData?.id ? '编辑' : '新增'
})

function closeDialog() {
  resetForm(ruleFormRef.value)
  emit('update:visible', false)
  emit('update:data', null)
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    let result: ApiResult<any>
    if (valid) {
      submitLoading.value = true
      if (formData?.id) {
        result = await updateSysDict(formData)
      } else {
        result = await saveSysDict(formData)
      }
      const { success, msg } = result
      submitLoading.value = false
      if (!success) {
        ElMessage.error(msg)
        return
      }
      closeDialog()
      emit('submit')
    } else {
      console.log('error submit!', fields)
    }
  })
}

watch(dialogVisible, (visible) => {
  Object.keys(formData).forEach((key: any) => {
    formData[key as keyof IDate] = visible ? props.data?.[key] || '' : ''
  })
  formData.state = Number(formData.state || 1)
  formData.sort = Number(formData.sort || 1)
})
</script>

<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    :title="`${title}${props.type === '1' ? '字典编码' : '字典值'}`"
    width="50%"
  >
    <el-form
      ref="ruleFormRef"
      :model="formData"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="字典名称" prop="name">
            <el-input v-model="formData.name" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="`${props.type === '1' ? '字典编码' : '字典值'}`" prop="code">
            <el-input v-model="formData.code" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字典排序" prop="sort">
            <el-input-number v-model="formData.sort" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字典状态" prop="state">
            <el-switch :active-value="1" :inactive-value="2" v-model="formData.state" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="字典说明" prop="remark">
            <el-input
              style="width: 100%"
              v-model="formData.remark"
              :autosize="{ minRows: 2, maxRows: 4 }"
              type="textarea"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="footer">
      <el-button @click="submitForm(ruleFormRef)" type="primary" :loading="submitLoading">
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
</style>
